home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: newsfeed.internetmci.com!xmission!news
  2. From: tknarr@xmission.com     ( Todd Knarr )
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: two tricky questions
  5. Date: 31 Dec 1995 21:28:30 GMT
  6. Organization: Chaos Central
  7. Message-ID: <4c6v9u$jdl@news.xmission.com>
  8. References: <4c4tbn$ga9@sunburst.ccs.yorku.ca> <4c5dn1$j5r@news.xmission.com>
  9. Reply-To: tknarr@xmission.com   ( Todd Knarr )
  10. NNTP-Posting-Host: slc149.xmission.com
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4c4tbn$ga9@sunburst.ccs.yorku.ca>, cs932082@ariel.cs.yorku.ca (Lila Behzadi) writes:
  14. >if I add "a=0" in the defult constructor of class A ; I will get the
  15. >following output and the problem will be solved:
  16.  
  17. It turns out there's another potential problem I overlooked. You do not
  18. define a copy constructor, so the compile will generate one that does a
  19. memberwise ( or bitwise ) assignment of the original to the copy. This is
  20. not good, because after this both the original and the copy have pointers
  21. to the same memory in them. When the original is destroyed that memory
  22. will be freed by delete, leaving a dangling pointer in the copy to foul
  23. up both references to it *and* the delete when the copy is destroyed. It
  24. is legal for the compiler, in your code, to create a temporary and initialize
  25. aaa via the copy constructor ( stupid, but legal ), leaving you deleting
  26. the same memory twice.
  27.  
  28. In general, I've found that classes that allocate dynamic memory and use
  29. pointers to it also need non-trivial copy constructors and copy assignment
  30. operators to avoid exactly this sort of problem.
  31.  
  32. --
  33. Todd Knarr : tknarr@xmission.com      |  finger for PGP public key
  34.                                       |  Member, USENET Cabal
  35.  
  36. Seriously, I don't want to die just yet.  I don't care how
  37. good-looking they are, I! don't! want! to! die!"
  38.                                         -- Megazone ( UF1 )
  39.  
  40.